//
//  LTChooseUnitView.m
//  LearnTeacher
//
//  Created by 高刘通 on 2024/6/7.
//

#import "LTChooseUnitView.h"
#import "LTChooseUnitCell.h"
#import "LTChooseUnitModel.h"

@interface LTChooseUnitView()<UITableViewDelegate, UITableViewDataSource>
@property(strong, nonatomic) UITableView *contentTableView;
@property(strong, nonatomic) UIView *bottomView;
@end

@implementation LTChooseUnitView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.contentTableView];
        [self addSubview:self.bottomView];
    }
    return self;
}

- (void)setDataSource:(NSArray *)dataSource {
    _dataSource = dataSource;
    [self.contentTableView reloadData];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.contentTableView.frame = CGRectMake(0, 49, self.width, self.height - 49 - [self safeBottom]);
    self.bottomView.frame = CGRectMake(0, self.contentTableView.height - 48 + self.contentTableView.top, self.width, 48 + [self safeBottom]);
}

- (CGFloat)safeBottom {
    return [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LTChooseUnitCell *cell = [tableView dequeueReusableCellWithIdentifier:@"leftCell" forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 48;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.didSelectHandler) {
        self.didSelectHandler(self.dataSource[indexPath.row]);
    }
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [UIView new];
        _bottomView.userInteractionEnabled = NO;
        _bottomView.backgroundColor = rgba(255, 255, 255, 0.8);
    }
    return _bottomView;
}

- (UITableView *)contentTableView {
    if (!_contentTableView) {
        _contentTableView = [self setupTableView];
        _contentTableView.contentInset = UIEdgeInsetsMake(0, 0, 48, 0);
        _contentTableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 48, 0);
    }
    return _contentTableView;
}

- (UITableView *)setupTableView {
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.estimatedRowHeight = 0;
    tableView.exclusiveTouch = YES;
    [tableView registerClass:[LTChooseUnitCell class] forCellReuseIdentifier:@"leftCell"];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return tableView;
}

@end

